package com.youngball.shiro.filter;

import com.alibaba.druid.support.json.JSONUtils;
import com.youngball.business.utill.DomainClubUtils;
import com.youngball.business.utill.ObjectNullUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by asus on 2016/6/11.
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    public static final Logger logger1 = LoggerFactory.getLogger("myTest1");

    @SuppressWarnings("Duplicates")
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
      HttpServletRequest req= (HttpServletRequest) request;
        String clubId3= request.getParameter("clubId");
        if (ObjectNullUtils.isNotBlank(clubId3)){
            DomainClubUtils.setCludId(clubId3);
        }else {
            String clubId2 = req.getHeader("clubId");
            if ( ObjectNullUtils.isNotBlank(clubId2)) {
                DomainClubUtils.setCludId(clubId2);
            }
        }
        logger1.debug("=======请求数据类型=========="+req.getContentType()+"===============");
        if(req.getContentType().contains("application/x-www-form-urlencoded")){
            return super.createToken(request, response);
        }else {
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = null;
            Map map=new HashMap();
            HttpServletRequest httpServletRequest= (HttpServletRequest) request;
            try {
                reader = request.getReader();
                String b = null;
                while ((b = reader.readLine()) != null){
                    sb.append(b);
                }
                map = (Map) JSONUtils.parse(sb.toString());
                System.out.print(map);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String username = (String) map.get("username");
            String password = (String) map.get("password");
            return createToken(username,password,request, response);
        }
    }

    @Override
    public void setLoginUrl(String loginUrl) {
        super.setLoginUrl("/sys/login");
    }

    @Override
    public void setPasswordParam(String passwordParam) {
        super.setPasswordParam("password");
    }

    @Override
    public void setUsernameParam(String usernameParam) {
        this.setUsernameParam("username");
    }

    @Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        request.getRequestDispatcher(getSuccessUrl()).forward(request, response);
    }

    /**
     * 重写executeLogin方法
     * 登录后重新生成sessionid
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        AuthenticationToken token = createToken(request, response);
        if (token == null) {
            String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
                    "must be created in order to execute a login attempt.";
            throw new IllegalStateException(msg);
        }
        try {
            Subject subject = getSubject(request, response);
            //获取session数据
            Session session = subject.getSession();
            final LinkedHashMap<Object, Object> attributes = new LinkedHashMap<Object, Object>();
            final Collection<Object> keys = session.getAttributeKeys();
            for (Object key : keys) {
                final Object value = session.getAttribute(key);
                if (value != null) {
                    attributes.put(key, value);
                }
            }
            session.stop();
            subject.login(token);
            // 登录成功后复制session数据
            session = subject.getSession();
            for (final Object key : attributes.keySet()) {
                session.setAttribute(key, attributes.get(key));
            }
            return onLoginSuccess(token, subject, request, response);
        } catch (AuthenticationException e) {
            return onLoginFailure(token, e, request, response);
        }
//        return super.executeLogin(request, response);
    }

    @Override
    protected AuthenticationToken createToken(String username, String password, ServletRequest request, ServletResponse response) {
        boolean rememberMe = true;
        String host = this.getHost(request);
        return this.createToken(username, password, rememberMe, host);
    }
}
